package com.base.vistter.iframe.service;

import com.base.vistter.iframe.constant.FileConstant;
import com.base.vistter.iframe.entity.SysProject;
import com.base.vistter.iframe.exception.IframeException;
import com.base.vistter.iframe.mapper.SysProjectMapper;
import com.base.vistter.iframe.properties.MinioProperties;
import com.base.vistter.iframe.template.MinioTemplate;
import com.base.vistter.iframe.utils.UploadUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
@Transactional
@Slf4j
public class SysProjectService extends BaseService<SysProjectMapper, SysProject> {

    @Resource(name = "minioTemplate")
    private MinioTemplate minioTemplate;
    @Resource(name = "minioProperties")
    private MinioProperties minioProperties;

    private static final DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHH");

    @Transactional(propagation = Propagation.REQUIRED)
    public boolean save(SysProject entity) throws IframeException {
        entity.setIcon(this.getIcon(entity.getLogo()));
        return super.updateById(entity);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public boolean updateById(SysProject entity) throws IframeException {
        SysProject project = super.getById(entity.getId());
        if(!project.getLogo().equals(entity.getLogo())){
            entity.setIcon(this.getIcon(entity.getLogo()));
        }
        return super.updateById(entity);
    }

    private String getIcon(String logo) throws IframeException{
        InputStream inputStream = null;
        try {
            inputStream = minioTemplate.downloadFile(logo);
            BufferedImage bufferedImage = UploadUtils.getScaledInstance(ImageIO.read(inputStream) , 64, 64);
            String filePath =  dateFormat.format(new Date()) + UploadUtils.getRandom() + FileConstant.SPRIT + UploadUtils.getFileName(logo) + FileConstant.ICON_SUFFIX;
            minioTemplate.uploadFile(minioProperties.getBucketName() ,filePath, UploadUtils.bufferedImageToInputStream(bufferedImage));
            return minioProperties.getBucketName() + FileConstant.SPRIT + filePath;
        }catch (IOException e){
            e.printStackTrace();
            log.error(e.getMessage());
        } finally {
            try {
                if(inputStream != null){
                    inputStream.close();
                }
            }catch (IOException e){
                log.error(e.getMessage());
                e.printStackTrace();
            }
        }
        return null;
    }

}
